package com.example.compose.retrofit.crash

import com.example.compose.retrofit.NetWorkManager
import com.example.compose.utils.DataStoreManager
import com.example.compose.utils.FileUtils
import com.example.compose.utils.LogUtil
import com.google.gson.Gson
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.system.exitProcess

class AddAppArashToRemotely {

    fun uploadCrashInfo(crash: Crash, thread: Thread? = null, throwable: Throwable? = null) {
        val uploadCrashInfo = NetWorkManager.getRequest().uploadCrashInfo(
            mutableMapOf(
                "app_name" to crash.name,
                "app_package" to crash.package_,
                "app_channel" to crash.channel,
                "phone_system" to crash.system,
                "phone_brands" to  crash.brands,
                "phone_model" to crash.model,
                "phone_system_version" to crash.systemVersion,
                "app_version_name" to crash.versionName,
                "app_version_code" to crash.versionCode
            )
        )

        uploadCrashInfo.enqueue(object : Callback<JSONObject> {
            override fun onResponse(call: Call<JSONObject>, response: Response<JSONObject>) {
                thread?.let {
                    throwable?.let{
                        exitProcess(0)
                    }

                }
            }

            override fun onFailure(call: Call<JSONObject>, t: Throwable) {
                t.message?.let { LogUtil.e("日志上传失败$it") }
                val crashJson = Gson().toJson(crash)
                val file = FileUtils.writeStringToFile(
                    "log/crash${System.currentTimeMillis()}.json",
                    crashJson,
                    2
                )

                GlobalScope.launch {
                    file?.parentFile?.absolutePath?.let{
                        DataStoreManager.saveLogcatFile(it)
                    }
                    thread?.let {
                        throwable?.let{
                            exitProcess(0)
                        }
                    }
                }

            }
        })
    }
}